/**
 * Copyright(c) 2016-2019 by Euler
 * All Rights Reserved
 */
package com.booter.producer.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

//import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author admin
 */
@RestController
public class UserController {

    //@PostConstruct
    public void init() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("user/index");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        rule.setClusterMode(true);

        ClusterFlowConfig cluster = new ClusterFlowConfig();
        cluster.setFallbackToLocalWhenFail(false);
        cluster.setThresholdType(1);
        cluster.setFlowId(1L);
        rule.setClusterConfig(cluster);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("user/index")
    public String index(@RequestParam String id) {
        Entry entry = null;
        try {
            entry = SphU.entry("user/index");
            System.out.println("time=" + System.currentTimeMillis() + ",entry=" + entry.getCurNode());
            return "ok:" + id;
        } catch (BlockException ex) {
            // 处理被流控的逻辑
            System.out.println("blocked!");
            Tracer.traceEntry(ex, entry);
            return "blocked";
        } finally {
            if (entry != null) {
                entry.close();
            }
        }

    }


    @SentinelResource("user/index2")
    @RequestMapping("user/index2")
    public String index2(@RequestParam String id) {
        System.out.println("time=" + System.currentTimeMillis());
        return "index2 ok:" + id;
    }

    /**
     * 用于监控检查 ，若集成了actuator，则默认的健康检查地址是actuator/health
     *
     * @return
     */
    @RequestMapping(value = "/hi")
    public String check() {
        return "ok";
    }


//    @RequestMapping("user/bitmap/{offset}")
//    public String bitmap(@PathVariable Long offset) {
//        this.redisTemplate.opsForValue().setBit("key-2", offset, true);
//        return "ok";
//    }

//    @RequestMapping("user/lock")
//    public Object lock(@RequestParam  String key ){
//        return redisTemplate.execute((RedisCallback<Boolean>) connection -> {
//            RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
//            RedisSerializer keySerializer = redisTemplate.getKeySerializer();
//            Object obj = connection.execute("set", keySerializer.serialize(key),
//                    valueSerializer.serialize("1"),
//                    "NX".getBytes(),
//                    "EX".getBytes(),
//                    String.valueOf(20 * 60L).getBytes());
//            return obj != null;
//        });
//    }


//    @Autowired
//    private UserMongoDao userMongoDao;
//
//    @RequestMapping("mongo/tx")
//    public String tx() {
//        this.userMongoDao.save();
//        return "ok";
//    }

}